package com.xywang.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import com.xywang.dao.BaseDao;
import com.xywang.pojo.Role;
import com.xywang.pojo.User;
import com.xywang.service.role.RoleService;
import com.xywang.service.role.RoleServiceImpl;
import com.xywang.service.user.UserService;
import com.xywang.service.user.UserServiceImpl;
import com.xywang.util.Constants;
import com.xywang.util.PageSupport;
import org.junit.Test;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class ServletUser extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method != null && method.equals("savepwd")) {
            this.updatePwdServlet(req, resp);
        }else if(method != null && method.equals("pwdmodify")){
            this.pwdModify(req, resp);
        }else if(method != null && method.equals("query")){
            this.query(req, resp);
        }else if("add".equals(method)){
            this.add(req, resp);
        }else if("getrolelist".equals(method)){
            this.getRoleList(req, resp);
        }else if("ucexist".equals(method)){
            this.userCodeExist(req, resp);
        }else if("deluser".equals(method)){
            this.deluser(req, resp);
        }else if("modify".equals(method)){
            this.modifygetUser(req, resp);
        }else if("modifyexe".equals(method)){
            this.modifyexe(req, resp);
        }else if("view".equals(method)){
            this.view(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    // 更新修改密码
    public void updatePwdServlet(HttpServletRequest req, HttpServletResponse resp){
        // 从session拿id
        Object attribute = req.getSession().getAttribute(Constants.USER_SESSION);
        String newpassword = req.getParameter("newpassword");
        boolean flag = false;

        // 判断attribute（user对象）不为空，且newpassword不为空
        if(attribute!=null && !StringUtils.isNullOrEmpty(newpassword)){
            UserService userService = new UserServiceImpl();
            // 更新数据库中的密码，返回是否成功的boolean值
            flag = userService.updatePwd(((User) attribute).getId(), newpassword);
            if(flag){
                req.setAttribute(Constants.MESSAGE,"修改密码成功，请退出，使用新密码登录!");
                // 密码修改成功，移除当前session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else{
                req.setAttribute(Constants.MESSAGE,"密码修改失败！");
            }
        }else{
            req.setAttribute(Constants.MESSAGE,"新密码有问题！");
        }
        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //验证旧密码，session中有用户的密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
        // 从session中拿到password
        Object attribute = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

        // 从session拿user对象，从表单拿输入的旧密码，创建哈希图存结果，转换为json的
        // 形式，以key--values键值对的形式，作为json数据流写到前端，前端js文件通过
        // result 取到值，再做判断
        Map<String, String> resultMap = new HashMap<String, String>();

        if(attribute==null){
            //Session失效了 或 session过期了
            resultMap.put("result","sessionerror");
        }else if(StringUtils.isNullOrEmpty(oldpassword)){
            // 旧密码为空
            resultMap.put("result","error");
        }else{
            String userPassword = ((User) attribute).getUserPassword();
            if(oldpassword.equals(userPassword)){
                resultMap.put("result","true");
            }else{
                resultMap.put("result","false");
            }
        }
        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            //JSONArray 阿组巴巴JSON工具类，转换格式
            /*
                resultMap=["result"，"sessionerror"，"result"，"error"]
                Json格式={key:value}
            */
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    // 展示用户列表
    public void query(HttpServletRequest req, HttpServletResponse resp){
        // 从前端获取值
        String queryUserName = req.getParameter("queryname");
        String queryTempUserRole = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");

        // 创建服务层对象，调用方法
        UserService userService = new UserServiceImpl();
        // 角色默认为0，就是没有角色
        int queryUserRole = 0;

        // 第一次走这个请求，一定是第一页，页面大小固定的
        int pageSize = BaseDao.getPageSize();// 可以把这个写到配置文件中，方便后期修改：
        int currentPageNo=1;

        // 用户名
        if (queryUserName == null) {
            /* 如果为空，则手动赋值,假如没有赋值，则null会被当作参数传递到dao层，
           以【 %null% 】作为参数运行sql语句，结果是什么都查不到，
           赋值后以【 %% 】为参数执行sql，会查出所有用户
            */
            queryUserName = "";
        }
        // 角色
        if (queryTempUserRole != null && !queryTempUserRole.equals("")) {
            queryUserRole = Integer.parseInt(queryTempUserRole);// 给查询赋值 0\1\2\3
        }
        // 当前‘页’
        if (pageIndex != null) {
            try{
                currentPageNo = Integer.parseInt(pageIndex);
            }catch (Exception e){
                try {
                    resp.sendRedirect(req.getContextPath()+"/error.jsp");
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }

        // 获取用户总条数 (分页 ：上一页，下一页)
        int userTotalCount = userService.getUserCount(queryUserName, queryUserRole);

        // 总页数支持
        /*
            将 当前页、页面大小、用户总数量传给 PageSupport 类，
            然后根据参数获取总页数
        */
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(userTotalCount);
        // 总页数 getTotalPageCount()
        int totalPageCount = pageSupport.getTotalPageCount();
        // 控制首页和尾页
        if(currentPageNo<1){
            currentPageNo = 1;
        }else if(currentPageNo>totalPageCount){
            currentPageNo = totalPageCount;
        }

        // 获取用户列表
        List<User> userList = null;
        // System.out.println("queryUserName ： "+queryUserName);
        // System.out.println("queryUserRole ： "+queryUserRole);
        // System.out.println("currentPageNo ： "+currentPageNo);
        // System.out.println("pageSize ： "+pageSize);
        // 获取用户列表展示
        userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
        // 通过请求req，将参数传给前端页面
        req.setAttribute("userList",userList);

        // 获取角色列表，通过请求req，将参数传给前端页面
        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleListService = roleService.getRoleListService();
        req.setAttribute("roleList",roleListService);

        // 分页
        req.setAttribute("totalCount",userTotalCount);// 用户总数
        req.setAttribute("currentPageNo",currentPageNo);// 当前页
        req.setAttribute("totalPageCount",totalPageCount);// 总页数

        req.setAttribute("queryUserName", queryUserName); // 用户名
        req.setAttribute("queryUserRole",queryTempUserRole);// 角色
        try {
            // 请求转发到 userlist.jsp 用户列表页面 同时携带上面设置的数据
            req.getRequestDispatcher("userlist.jsp").forward(req, resp);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }

    // 添加用户
    public void add(HttpServletRequest req, HttpServletResponse resp){
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        User user = new User();
        // 将表单提交的数据封装到user对象
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());

        System.out.println("ServletUser : "+user.toString());
        UserServiceImpl userService = new UserServiceImpl();
        if (userService.addUserService(user)) {
            try {
                resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                req.getRequestDispatcher("useradd.jsp").forward(req, resp);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 获取添加用户时角色选项的角色列表
    public void getRoleList(HttpServletRequest req, HttpServletResponse resp){
        List<Role> roleList = null;
        RoleService roleService = new RoleServiceImpl();
        roleList = roleService.getRoleListService();
        //把roleList转换成json对象输出

        PrintWriter outPrintWriter = null;
        try {
            // 以"application/json"类型响应
            resp.setContentType("application/json");
            // 获取响应流
            outPrintWriter = resp.getWriter();
            // roleList转换为json输出到前端
            outPrintWriter.write(JSONArray.toJSONString(roleList));
            // System.out.println("roleList转换为json输出到前端:"+JSONArray.toJSONString(roleList));
            // 刷新、关闭
            outPrintWriter.flush();
            outPrintWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 添加用户时判断用户userCode是否已存在
    public void userCodeExist(HttpServletRequest req, HttpServletResponse resp){
        //判断用户账号是否可用
        String userCode = req.getParameter("userCode");

        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (StringUtils.isNullOrEmpty(userCode)) {
            //userCode == null || userCode.equals("")
            resultMap.put("userCode", "exist");
        } else {
            UserService userService = new UserServiceImpl();
            User user = userService.selectUserCode(userCode);
            if (null != user) {
                resultMap.put("userCode", "exist");
            } else {
                resultMap.put("userCode", "notexist");
            }
        }

        //把resultMap转为json字符串以json的形式输出
        PrintWriter outPrintWriter = null;
        try {
            //配置上下文的输出类型
            resp.setContentType("application/json");
            //从response对象中获取往外输出的writer对象
            outPrintWriter = resp.getWriter();
            //把resultMap转为json字符串 输出
            outPrintWriter.write(JSONArray.toJSONString(resultMap));
            outPrintWriter.flush();//刷新
            outPrintWriter.close();//关闭流
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // 删除用户
    public void deluser(HttpServletRequest req, HttpServletResponse resp){
        String id = req.getParameter("uid");
        int delId = 0;
        try {
            delId = Integer.parseInt(id);
        } catch (Exception e) {
            delId = 0;
        }
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (delId <= 0) {
            resultMap.put("delResult", "notexist");
        } else {
            UserService userService = new UserServiceImpl();
            if (userService.deleteUserService(delId)) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        }

        //把resultMap转换成json对象输出
        PrintWriter outPrintWriter = null;
        try {
            resp.setContentType("application/json");
            outPrintWriter = resp.getWriter();
            outPrintWriter.write(JSONArray.toJSONString(resultMap));
            outPrintWriter.flush();
            outPrintWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // 修改用户
    public void modifyexe(HttpServletRequest req, HttpServletResponse resp){
        String uid = req.getParameter("uid");
        String userName = req.getParameter("userName");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        User user = new User();
        user.setId(Integer.valueOf(uid));
        user.setUserName(userName);
        user.setGender(Integer.valueOf(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.valueOf(userRole));
        user.setModifyBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());

        UserService userService = new UserServiceImpl();
        if (userService.updateUserService(user)) {
            try {
                resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                req.getRequestDispatcher("usermodify.jsp").forward(req, resp);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
        }


    }
    // 通过id获取用户转发给usermodify
    public void modifygetUser(HttpServletRequest req, HttpServletResponse resp){
        String uid = req.getParameter("uid");
        if (!StringUtils.isNullOrEmpty(uid)) {
            //调用后台方法得到user对象
            UserService userService = new UserServiceImpl();
            User user = userService.getUserByIdService(Integer.parseInt(uid));
            req.setAttribute("user", user);
            try {
                req.getRequestDispatcher("usermodify.jsp").forward(req, resp);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 查看用户详细
    public void view(HttpServletRequest req, HttpServletResponse resp){
        String uid = req.getParameter("uid");
        if (!StringUtils.isNullOrEmpty(uid)) {
            //调用后台方法得到user对象
            UserService userService = new UserServiceImpl();
            User user = userService.getUserByIdService(Integer.parseInt(uid));
            req.setAttribute("user", user);
            try {
                req.getRequestDispatcher("userview.jsp").forward(req, resp);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Test
    public void test(){

    }

}
